var express = require('express')
var sd = require('silly-datetime')
var Yo = require('../models/yo')
var YoDetail = require('../models/yodetail')
var ObjectID = require('mongodb').ObjectID
/// 获取全部列表
function yo(req, res) {
    Yo.find((error, result)=> {
        if (error) {
            return res.end(error.message)
        }
        let data = {"data": result}
        return res.end(JSON.stringify(data))
    })
}
/// 添加
function add(req, res) {
    let params = '';
    req.on('data', (bf) => {
        params += bf
    })
    req.on('end', (bf) => {
        let parameters = JSON.parse(params)
        new Yo(parameters).save((error, result)=> {
            if (error) {
                res.end(error.message)
            }
            saveDetail(parameters).then((data)=> {
                yo(req, res)
            }).catch((error)=> {
                res.end(error.message)
            })
        })
    })
}
///同步更新详情
function saveDetail(para) {
    return new Promise((resolve, reject)=> {
        new YoDetail({
            name: para.name,
            cluster: para.cluster,
            denominator: para.denominator,
            numerator: para.numerator,
            today: 0,
            desc: []
        }).save((error, result)=> {
            if (error) {
                reject(error)
            }
            resolve(result)
        })
    })
}
/// 删除
function deleteYo (req, res) {
    let params = '';
    req.on('data', (bf) => {
        params += bf
    })
    req.on('end', (bf) => {
        let parameters = JSON.parse(params)
        Yo.findById({"_id": new ObjectID(parameters.id)}, (error, result)=> {
            if (error) {
                res.end(error.message)
            }
            YoDetail.deleteOne({"name": result.name}, (error, result)=> {
                if (error) {
                    res.end(error.message)
                }
                Yo.deleteOne({"_id": new ObjectID(parameters.id)}, (error, result)=> {
                    if (error) {
                        res.end(error.message)
                    }
                    yo(req, res)
                })
            })
        })
    })
}
/// 同步更新详情
function deleteDetail(id) {
    fs.readFile('./public/sources/YoDetail.json', (error, data) => {
        if (error) {
            console.log('读取数据失败');
            return
        }
        let detail = JSON.parse(data)
        let details = detail.data
        details.forEach((item, index) => {
            if (item.id === id) {
                details.splice(index, 1)
            }
        });
        details.forEach((item, index) => {
            item.id = index + 1
        });
        detail.data = details
        let newJSON = JSON.stringify(detail)
        fs.writeFile('./public/sources/YoDetail.json', newJSON, (error) => {
            if (error) {
                console.log('文件更新失败');
            } else {
                console.log('文件更新成功');
            }

        })
    })
}
///获取详情
function detail(req, res) {
    let params = '';
    req.on('data', (bf) => {
        params += bf
    })
    req.on('end', (bf) => {
        let parameters = JSON.parse(params)
        Yo.findById({"_id": new ObjectID(parameters.id)}, (error, result)=> {
            if (error) {
                res.end(error.message)
            }
            YoDetail.findOne({"name": result.name}, (error, result)=> {
                if (error) {
                    res.end(error.message)
                }
                let desc = result.desc
                let lastPunch = ""
                if (desc.length) {
                    lastPunch = desc[desc.length -1].time
                }
                let now = sd.format(new Date(), 'MM-DD')
                if (lastPunch !== now) {
                    YoDetail.findByIdAndUpdate({"_id": result.id}, {today: 0}, (error, result)=> {
                        if (error) {
                            res.end(error.message)
                        }
                        YoDetail.findById({"_id": result.id}, (error, result)=> {
                            if (error) {
                                res.end(error.message)
                            }
                            let data = { "data": result }
                            let newJSON = JSON.stringify(data)
                            res.end(newJSON)
                        })
                    })
                } else {
                    let data = { "data": result }
                    let newJSON = JSON.stringify(data)
                    res.end(newJSON)
                }
            })
        })
    })
}

///打卡
function punched(req, res) {
    let params = '';
    req.on('data', (bf) => {
        params += bf
    })
    req.on('end', (bf) => {
        let parameters = JSON.parse(params)
        YoDetail.findById({"_id": new ObjectID(parameters.id)}, (error, result)=> {
            if (error) {
                res.end(error.message)
            }
            let desc = {}
            desc.time = sd.format(new Date(), 'MM-DD')
            desc.today = parameters.today
            desc.text = parameters.text
            result.desc.push(desc)
            YoDetail.updateOne({"_id": new ObjectID(parameters.id)}, {desc: result.desc, today: parameters.today}, (error)=> {
                if (error) {
                    res.end(error.message)
                }
                updateyo(result.name, parameters.today + result.numerator).then((data)=> {
                    YoDetail.findById({"_id": new ObjectID(parameters.id)}, (error, result)=> {
                        if (error) {
                            res.end(error.message)
                        }
                        let data = { "data": result }
                        let newJSON = JSON.stringify(data)
                        res.end(newJSON)
                    })
                }).catch((error)=> {
                    res.end(error.message)
                })
                
            })
        })
    })
}
///同步外围数据
function updateyo(name, num) {
    return new Promise((resolve, reject)=> {
        Yo.findOneAndUpdate({"name": name}, {numerator: num}, (error, result)=> {
            if (error) {
                reject(error)
            }
            resolve(result)
        })
    })
}


module.exports = {
    yo, add, deleteYo, detail, punched
}